package com.rainbowred.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.rainbowred.common.controller.BaseController;
import com.rainbowred.common.enums.ErrorCode;
import com.rainbowred.common.execption.BusinessException;
import com.rainbowred.common.pojo.CommonResult;
import com.rainbowred.common.util.OkHttpUtils;
import com.rainbowred.common.util.StringUtil;
import com.rainbowred.common.util.aes.AESEncodingUtil;
import com.rainbowred.common.util.aes.AesException;
import com.rainbowred.common.util.aes.SHA1;
import com.rainbowred.system.domain.EdpDeveloper;
import com.rainbowred.system.service.EdpDeveloperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Desc:
 * @Date: 2023/10/27 15:04
 * @Author: pengweibiao
 **/
@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController extends BaseController {

    @Autowired
    private EdpDeveloperService service;

    /**
     * 文档页前端 接口请求
     * @param param
     * @return
     */
    @GetMapping("")
    public CommonResult<Object> validCode(@RequestParam Map<String, String> param) {
        // 校验参数
        validParam(param);
        // 获取开发者Id
        String devId = param.get("devId");
        // 查询数据
        EdpDeveloper developer = service.getById(devId);
        // 查询为空
        if (Objects.isNull(developer)) {
            throw new BusinessException(ErrorCode.E2001, "devId查询为空，联系管理员");
        }

        if (developer.getDisable().equals(1) || developer.getDelFlag().equals(1)) {
            throw new BusinessException(ErrorCode.E2001, "用户已受限，联系管理员");
        }

        // 校验signature
        validSignature(developer.getToken(), param);

        // 解密
        JSONObject data = decode(developer, param.get("code"));

        log.info("=====ApiController-validCode=====data====="+data.toJSONString());

        // 业务平台Url
        String serverUrl = (String) data.get("serverUrl");
        // 校验 serverUrl
        validServerUrl(serverUrl);

        // 自定义状态参数
        Object state = data.get("state");
        // 构建请求体
        Map<String, Object> body = null;
        if (Objects.nonNull(state)) {
            body = new HashMap<>();
            body.put("state", state);
        }

        // 请求业务服务器
        String response = OkHttpUtils.builder(10).url(serverUrl).post(JSONObject.toJSONString(body)).sync();

        log.info("=====ApiController-validCode=====response====="+response);

        // 校验返回格式
        JSONObject resJson = validResponseFormat(response);

        // 页面配置
        Object config = data.get("config");

        Map<String, Object> result = new HashMap<>();
        result.put("config", config);
        result.put("data", resJson.get("data"));

        return success(result);
    }

    /**
     * 校验参数
     * @param param
     */
    private void validParam(Map<String, String> param) {
        if (StringUtil.isEmpty(param.get("devId"))) {
            throw new BusinessException(ErrorCode.E1001, "参数devId为空");
        }
        if (StringUtil.isEmpty(param.get("tm"))) {
            throw new BusinessException(ErrorCode.E1001, "参数tm为空");
        }
        if (StringUtil.isEmpty(param.get("nonce"))) {
            throw new BusinessException(ErrorCode.E1001, "参数nonce为空");
        }
        if (StringUtil.isEmpty(param.get("signature"))) {
            throw new BusinessException(ErrorCode.E1001, "参数signature为空");
        }
        if (StringUtil.isEmpty(param.get("code"))) {
            throw new BusinessException(ErrorCode.E1001, "参数code为空");
        }
    }

    /**
     * 根据传入的参数 生成signature 校验
     * @param param 传入参数
     */
    private void validSignature(String token, Map<String, String> param) {
        // 校验signature
        if (!validSignature(token, param.get("signature"), param.get("tm"), param.get("nonce"))) {
            throw new BusinessException(ErrorCode.E1002);
        }
    }

    /**
     * 校验传入的url是否合法
     * @param serverUrl
     */
    private void validServerUrl(String serverUrl) {
        if (!serverUrl.startsWith("https://") && !serverUrl.startsWith("http://")) {
            throw new BusinessException(ErrorCode.E2003);
        }
    }

    private JSONObject validResponseFormat(String response) {
        // 转JSON对象
        JSONObject jsonObject = JSONObject.parseObject(response);
        // 判断返回码
        Integer code = (Integer) jsonObject.get("code");
        if (Objects.isNull(code)) {
            throw new BusinessException(ErrorCode.E3002, "code字段不存在");
        }
        if (!code.equals(200)) {
            String msg = (String) jsonObject.get("msg");
            throw new BusinessException(ErrorCode.E3002, "返回错误code："+ code + (msg == null ? "" : msg));
        }

        // 判断返回数据
        Object data = jsonObject.get("data");
        if (Objects.isNull(data)) {
            throw new BusinessException(ErrorCode.E3002, "data返回为空");
        }
        return jsonObject;
    }

    /**
     * Code解密
     * @param developer 开发者信息
     * @param code 密文
     * @return
     */
    private JSONObject decode(EdpDeveloper developer, String code) {
        // 获取解密参数
        String appid = developer.getAppid();
        String aeskey = developer.getAeskey();
        String token = developer.getToken();
        try {
            if (code.contains(" ")) {
                code = code.replace(" ", "+");
            }
            // 解密
            String s = AESEncodingUtil.jsonDecrypt(code, appid, aeskey, token);
            return JSONObject.parseObject(s);
        }catch (AesException e) {
            throw new BusinessException(ErrorCode.E2002);
        }
    }

}
